package org.dtrd.modules.archive.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.archive.entity.bean.report.DiabetesComplicationReport;
import org.dtrd.modules.archive.entity.po.DtrdEntRdArchiveComplication;
import org.dtrd.modules.archive.mapper.DtrdEntRdComplicationMapper;
import org.dtrd.modules.archive.service.IDtrdEntRdComplicationService;
import org.dtrd.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.StringJoiner;

/**
 * @author 萧
 * @date 2021-10-01 22:47:26
 **/
@Service
@DS("multi-datasource1")
public class DtrdEntRdComplicationServiceImpl extends ServiceImpl<DtrdEntRdComplicationMapper, DtrdEntRdArchiveComplication> implements IDtrdEntRdComplicationService {

    private final static String pubDossierRetinopathy = "pubDossierRetinopathy";

    private final static String pubDossierMe = "pubDossierMe";

    private final static String pubDossierRetinopathySymptom = "pubDossierRetinopathySymptom";

    private final static String retinopathyIntraRetinal = "retinopathyIntraRetinal";

    private final static String retinopathyExudate = "retinopathyExudate";

    private final static String retinopathyBeading = "retinopathyBeading";

    private final static String retinopathyMicrovascular = "retinopathyMicrovascular";

    private final static String pubDossierExtremitySymptom = "pubDossierExtremitySymptom";

    private final static String pubDossierKetoacidosisSymptom = "pubDossierKetoacidosisSymptom";

    @Autowired
    private ISysDictService dictService;

    @Override
    public DiabetesComplicationReport getPatientDiabetesComplicationReport(Integer patientId) {
        DtrdEntRdArchiveComplication po = getPatientDiabetesComplication(patientId);
        DiabetesComplicationReport report = null;
        if (po != null) {
            report = new DiabetesComplicationReport().parseFromPo(po);
            // 糖尿病视网膜病变
            Integer retinopathy = po.getRetinopathy();
            if (retinopathy != null && retinopathy.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setRetinopathyText(Constant.DiabetesDiagnose.valueOf(retinopathy).getName());
                report.setRetinopathyDate(DateUtil.formatDate(po.getRetinopathyDate()));
                StringJoiner retinopathyJoiner = new StringJoiner("; ");
                Integer staging = po.getRetinopathyStaging();
                if (staging != null) {
                    String stagingText = dictService.queryDictTextByKey(pubDossierRetinopathy, staging + "");
                    retinopathyJoiner.add("病变分期：" + stagingText);
                }
                Integer retinopathyMe = po.getRetinopathyMe();
                if (retinopathyMe != null) {
                    String text = dictService.queryDictTextByKey(pubDossierMe, retinopathyMe + "");
                    retinopathyJoiner.add("黄斑水肿：" + text);
                }
                String retinopathySymptom = po.getRetinopathySymptom();
                if (StrUtil.isNotBlank(retinopathySymptom)) {
                    String[] split = retinopathySymptom.split(",");
                    StringJoiner joiner = new StringJoiner(",");
                    for (String s : split) {
                        joiner.add(dictService.queryDictTextByKey(pubDossierRetinopathySymptom, s));
                    }
                    retinopathyJoiner.add("病变症状: " + joiner);
                }
                String visionLeft = po.getRetinopathyVision();
                String visionRight = po.getRetinopathyVisionRight();
                if (StrUtil.isNotBlank(visionLeft) && StrUtil.isNotBlank(visionRight)) {
                    String vision = String.format("视力：%s（左）/%s（右）", visionLeft, visionRight);
                    retinopathyJoiner.add(vision);
                }
                Integer microaneurysm = po.getRetinopathyMicroaneurysm();
                if (microaneurysm != null) {
                    retinopathyJoiner.add("微动脉瘤：" + Constant.YesOrNo.valueOf(microaneurysm).getName());
                }
                Integer intraRetinal = po.getRetinopathyIntraRetinal();
                if (intraRetinal != null) {
                    String text = dictService.queryDictTextByKey(retinopathyIntraRetinal, intraRetinal + "");
                    retinopathyJoiner.add("视网膜内出血: " + text);
                }
                Integer flock = po.getRetinopathyFlock();
                if (flock != null) {
                    retinopathyJoiner.add("棉絮斑：" + Constant.YesOrNo.valueOf(flock).getName());
                }
                String exudate = po.getRetinopathyExudate();
                if (StrUtil.isNotBlank(exudate)) {
                    String text = dictService.queryDictTextByKey(retinopathyExudate, exudate);
                    retinopathyJoiner.add("硬性渗出：" + text);
                }
                Integer beading = po.getRetinopathyBeading();
                if (beading != null) {
                    String text = dictService.queryDictTextByKey(retinopathyBeading, beading + "");
                    retinopathyJoiner.add("静脉串珠样改变: " + text);
                }
                Integer microvascular = po.getRetinopathyMicrovascular();
                if (microvascular != null) {
                    String text = dictService.queryDictTextByKey(retinopathyMicrovascular, beading + "");
                    retinopathyJoiner.add("视网膜内微血管异常: " + text);
                }
                Integer neovascularization = po.getRetinopathyNeovascularization();
                if (neovascularization != null) {
                    retinopathyJoiner.add("新生血管形成: " + Constant.YesOrNo.valueOf(neovascularization).getName());
                }
                Integer vitreous = po.getRetinopathyVitreous();
                if (vitreous != null) {
                    retinopathyJoiner.add("玻璃体积血: " + Constant.YesOrNo.valueOf(vitreous).getName());
                }
                Integer anteriorRetinal = po.getRetinopathyAnteriorRetinal();
                if (anteriorRetinal != null) {
                    retinopathyJoiner.add("视网膜前出血: " + Constant.YesOrNo.valueOf(anteriorRetinal).getName());
                }
                Integer retinalThickening = po.getRetinopathyRetinalThickening();
                if (retinalThickening != null) {
                    retinopathyJoiner.add("后极部视网膜增厚: " + Constant.YesOrNo.valueOf(retinalThickening).getName());
                }
                Integer fundusHemorrhage = po.getRetinopathyFundusHemorrhage();
                if (fundusHemorrhage != null) {
                    retinopathyJoiner.add("眼底出血: " + Constant.YesOrNo.valueOf(fundusHemorrhage).getName());
                }
                report.setRetinopathyData(retinopathyJoiner.toString());
            }
            // 糖尿病周围神经病变
            Integer peripheral = po.getPeripheral();
            if (peripheral != null && peripheral.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setPeripheralText(Constant.DiabetesDiagnose.valueOf(peripheral).getName());
                report.setPeripheralDate(DateUtil.formatDate(po.getPeripheralDate()));
                StringJoiner joiner = new StringJoiner(";");
                Integer acupuncture = po.getPeripheralAcupuncture();
                if (acupuncture != null) {
                    joiner.add("针刺痛觉: " + Constant.PeripheralItem.valueOf(acupuncture).getName());
                }
                Integer temperature = po.getPeripheralTemperature();
                if (temperature != null) {
                    joiner.add("温度觉: " + Constant.PeripheralItem.valueOf(temperature).getName());
                }
                Integer pressure = po.getPeripheralPressure();
                if (pressure != null) {
                    joiner.add("压力觉: " + Constant.PeripheralItem.valueOf(pressure).getName());
                }
                Integer vibration = po.getPeripheralVibration();
                if (vibration != null) {
                    joiner.add("振动觉: " + Constant.PeripheralItem.valueOf(vibration).getName());
                }
                Integer ankle = po.getPeripheralAnkle();
                if (ankle != null) {
                    joiner.add("踝反射: " + Constant.PeripheralItem.valueOf(ankle).getName());
                }
                Integer conduction = po.getPeripheralConduction();
                if (conduction != null) {
                    joiner.add("神经传导: " + Constant.PeripheralItem.valueOf(conduction).getName());
                }
                report.setPeripheralData(joiner.toString());
            }
            // 心血管自主神经病变
            Integer cardiovascular = po.getCardiovascular();
            if (cardiovascular != null && cardiovascular.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setCardiovascularText(Constant.DiabetesDiagnose.valueOf(cardiovascular).getName());
                report.setCardiovascularDate(DateUtil.formatDate(po.getCardiovascularDate()));
                StringJoiner joiner = new StringJoiner(";");
                Integer variability = po.getCardiovascularVariability();
                if (variability != null) {
                    joiner.add("心率变异性检查: " + Constant.NormalStatus.valueOf(variability).getName());
                }
                Integer valasalva = po.getCardiovascularValasalva();
                if (valasalva != null) {
                    joiner.add("Valasalva试验: " + Constant.NormalStatus.valueOf(valasalva).getName());
                }
                Integer hypotension = po.getCardiovascularHypotension();
                if (hypotension != null) {
                    joiner.add("体位性低血压变化测定: " + Constant.NormalStatus.valueOf(hypotension).getName());
                }
                Integer monitoring24 = po.getCardiovascularMonitoring24();
                if (monitoring24 != null) {
                    joiner.add("24h动态血压监测: " + Constant.NormalStatus.valueOf(monitoring24).getName());
                }
                Integer fist = po.getCardiovascularFist();
                if (fist != null) {
                    switch (fist) {
                        case 2:
                            joiner.add("握拳试验: 收缩压身高<=10mmHg");
                            break;
                        case 1:
                            joiner.add("握拳试验: 收缩压身高>10mmHg");
                            break;
                    }
                }
                report.setCardiovascularData(joiner.toString());
            }
            // 消化系统自主神经病变
            Integer digestive = po.getDigestive();
            if (digestive != null && digestive.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setDigestiveText(Constant.DiabetesDiagnose.valueOf(digestive).getName());
                report.setDigestiveDate(DateUtil.formatDate(po.getDigestiveDate()));
                StringJoiner joiner = new StringJoiner(";");
                Integer electrogastrogram = po.getDigestiveElectrogastrogram();
                if (electrogastrogram != null) {
                    joiner.add("胃电图: " + Constant.NormalStatus.valueOf(electrogastrogram).getName());
                }
                Integer sophageal = po.getDigestiveSophageal();
                if (sophageal != null) {
                    joiner.add("食管测压: " + Constant.NormalStatus.valueOf(sophageal).getName());
                }
                Integer scintillation = po.getDigestiveScintillation();
                if (scintillation != null) {
                    joiner.add("胃排空闪烁图扫描: " + Constant.NormalStatus.valueOf(scintillation).getName());
                }
                Integer digestiveRectum = po.getDigestiveRectum();
                if (digestiveRectum != null) {
                    joiner.add("直肠局部末梢神经病变电生理检查: " + Constant.NormalStatus.valueOf(digestiveRectum).getName());
                }
                report.setDigestiveData(joiner.toString());
            }
            // 泌尿生殖系统自主神经病变
            Integer genitourinary = po.getGenitourinary();
            if (genitourinary != null && genitourinary.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setGenitourinaryText(Constant.DiabetesDiagnose.valueOf(genitourinary).getName());
                report.setGenitourinaryDate(DateUtil.formatDate(po.getGenitourinaryDate()));
                StringJoiner joiner = new StringJoiner(";");
                Integer bladder = po.getGenitourinaryBladder();
                if (bladder != null) {
                    joiner.add("膀胱容量: " + Constant.NormalStatus.valueOf(bladder).getName());
                }
                Integer nerve = po.getGenitourinaryNerve();
                if (nerve != null) {
                    joiner.add("神经传导速度检查: " + Constant.NormalStatus.valueOf(nerve).getName());
                }
                report.setGenitourinaryData(joiner.toString());
            }
            //  糖尿病下肢血管病变
            Integer extremity = po.getExtremity();
            if (extremity != null && extremity.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setExtremityText(Constant.DiabetesDiagnose.valueOf(extremity).getName());
                report.setExtremityDate(DateUtil.formatDate(po.getExtremityDate()));
                StringJoiner joiner = new StringJoiner(";");
                String symptom = po.getExtremitySymptom();
                if (StrUtil.isNotBlank(symptom)) {
                    String[] strings = symptom.split(",");
                    StringJoiner joiner1 = new StringJoiner("、");
                    for (String s : strings) {
                        joiner1.add(dictService.queryDictTextByKey("pubDossierExtremitySymptom", s));
                    }
                    joiner.add("糖尿病下肢血管病变症状: " + joiner1);
                }
                Integer carotid = po.getExtremityCarotid();
                if (carotid != null) {
                    joiner.add("颈动脉听诊: " + Constant.AuscultationStatus.valueOf(carotid).getName());
                }
                Integer femoral = po.getExtremityFemoral();
                if (femoral != null) {
                    joiner.add("股动脉听诊: " + Constant.AuscultationStatus.valueOf(femoral).getName());
                }
                Integer skin = po.getExtremitySkin();
                if (skin != null) {
                    joiner.add("皮肤温度测定: " + Constant.NormalStatus.valueOf(skin).getName());
                }
                Integer dorsalandposterior = po.getExtremityDorsalandposterior();
                if (dorsalandposterior != null) {
                    joiner.add("足背/胫后动脉检查: " + Constant.NormalStatus.valueOf(dorsalandposterior).getName());
                }
                Integer vessel = po.getExtremityVessel();
                if (vessel != null) {
                    joiner.add("下肢血管: " + Constant.NormalStatus.valueOf(vessel).getName());
                }
                Integer claudication = po.getExtremityClaudication();
                if (claudication != null) {
                    joiner.add("间歇性跛行试验: " + Constant.YinYang.valueOf(claudication).getName());
                }
                Integer extremityAbi = po.getExtremityAbi();
                if (extremityAbi != null) {
                    joiner.add("ABI: " + Constant.ABI.valueOf(extremityAbi).getName());
                }
                Integer abiexercise = po.getExtremityAbiexercise();
                if (abiexercise != null) {
                    switch (abiexercise){
                        case 1:
                            joiner.add("ABI运动负荷试验: " + "0.9~1.3");
                            break;
                        case 2:
                            joiner.add("ABI运动负荷试验: " + "下降15%～20%");
                            break;
                    }
                }
                Integer extremityVessel = po.getExtremityVessel();
                if (extremityVessel != null){
                    switch (extremityVessel){
                        case 1:
                            joiner.add("下肢血管CTA/DSA/MR/B超:" + "正常");
                            break;
                        case 2:
                            joiner.add("下肢血管CTA/DSA/MR/B超:" + "提示血管病变");
                            break;
                        case 3:
                            joiner.add("下肢血管CTA/DSA/MR/B超:" + "其它");
                            break;
                    }
                }
                report.setExtremityData(joiner.toString());
            }
            // 糖尿病足
            Integer dfoot = po.getDfoot();
            if (dfoot != null && dfoot.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setDfootText(Constant.DiabetesDiagnose.valueOf(dfoot).getName());
                report.setDfootDate(DateUtil.formatDate(po.getDfootDate()));
                StringJoiner joiner = new StringJoiner(";");
                Integer ulcer = po.getDfootUlcer();
                if (ulcer != null) {
                    joiner.add("溃疡: " + Constant.Ulceration.valueOf(ulcer).getName());
                }
                Integer gangrene = po.getDfootGangrene();
                if (gangrene != null) {
                    joiner.add("坏疽: " + Constant.Gangrene.valueOf(gangrene).getName());
                }
                Integer infected = po.getDfootInfected();
                if (infected != null) {
                    joiner.add("感染: " + Constant.YesOrNo.valueOf(infected).getName());
                }
                Integer parenchyma = po.getDfootParenchyma();
                if (parenchyma != null) {
                    joiner.add("软组织炎: " + Constant.YesOrNo.valueOf(parenchyma).getName());
                }
                Integer abscess = po.getDfootAbscess();
                if (abscess != null) {
                    joiner.add("脓肿: " + Constant.YesOrNo.valueOf(abscess).getName());
                }
                Integer bone = po.getDfootBone();
                if (bone != null) {
                    joiner.add("骨组织感染: " + Constant.YesOrNo.valueOf(bone).getName());
                }
                Integer osteomyelitis = po.getDfootOsteomyelitis();
                if (osteomyelitis != null) {
                    joiner.add("脓肿或骨髓炎: " + Constant.YesOrNo.valueOf(osteomyelitis).getName());
                }
                Integer nerve = po.getDfootNerve();
                if (nerve != null) {
                    joiner.add("神经传导功能: " + Constant.NormalStatus.valueOf(nerve).getName());
                }
                Float abi = po.getDfootAbi();
                if (abi != null) {
                    joiner.add("ABI: " + abi);
                }
                String xray = po.getDfootXray();
                if (StrUtil.isNotBlank(xray)) {
                    joiner.add("足X线: " + xray);
                }
                String ulcerative = po.getDfootUlcerative();
                if (StrUtil.isNotBlank(ulcerative)) {
                    joiner.add("溃疡组织培养药敏试验: " + ulcerative);
                }
                Integer extremityb = po.getDfootExtremityb();
                if (extremityb != null) {
                    switch (extremity){
                        case 1:
                            joiner.add("下肢血管B超: " + "正常");
                            break;
                        case 2:
                            joiner.add("下肢血管B超: " + "提示下肢血管病变");
                            break;
                        case 3:
                            joiner.add("下肢血管B超: " + "其它");
                            break;
                    }

                }
                report.setDfootData(joiner.toString());
            }
            // 酮症酸中毒
            Integer dka = po.getDka();
            if (dka != null && dka.equals(Constant.DiabetesDiagnose.DIAGNOSE.getType())) {
                report.setDkaText(Constant.DiabetesDiagnose.valueOf(dka).getName());
                report.setDkaDate(DateUtil.formatDate(po.getDkaIsDate()));
                StringJoiner joiner = new StringJoiner(";");
                String dkaSymptom = po.getDkaSymptom();
                if (StrUtil.isNotBlank(dkaSymptom)) {
                    String[] strings = dkaSymptom.split(",");
                    StringJoiner joiner1 = new StringJoiner("、");
                    for (String s : strings) {
                        String text = dictService.queryDictTextByKey(pubDossierKetoacidosisSymptom, s);
                        joiner1.add(text);
                    }
                    joiner.add("酮症酸症状: " + joiner1);
                }
                Float bloodKetone = po.getDkaIsBloodKetone();
                if (bloodKetone != null) {
                    joiner.add("血酮体: " + bloodKetone);
                }
                Float bloodGas = po.getDkaIsBloodGas();
                if (bloodGas != null) {
                    joiner.add("血气分析: " + bloodGas);
                }
                report.setDkaData(joiner.toString());
            }

        }
        return report;
    }

    @Override
    public DtrdEntRdArchiveComplication getPatientDiabetesComplication(Integer patientId) {
        return getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveComplication.class)
                .eq(DtrdEntRdArchiveComplication::getPatientId, patientId)
                .eq(DtrdEntRdArchiveComplication::getIsDel, 0)
                .last(" limit 1 ")
        );
    }
}
